﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Web.Script.Services;
using SPAzureBlobField.Classes;
using System.ServiceModel;
using Microsoft.SharePoint;
using System.Runtime.Serialization;
using System.Web;

namespace SPAzureBlobField.Services
{
    [ServiceContract(Name = "AzureBlobService", Namespace = "AzureBlobServices")]
    public interface IAzureBlobServices
    {
        [OperationContract]
        bool IsSLClientOpenedForUser();

        [OperationContract]
        void CreateSession();

        [OperationContract]
        void InitiateBlobTransfert(string listId, string itemId, string fieldId, string blobId, bool isUpload);

        [OperationContract]
        List<Blob> fetchBlobsToDownload();

        [OperationContract]
        void ValidateBlob(string guid, string name);

        [OperationContract]
        void IAmAlive();

        [OperationContract]
        string GetShareLink(string listId, string itemId, string fieldId, string blobId);
    }

    [ScriptService]
    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    [BasicHttpBindingServiceMetadataExchangeEndpoint]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class AzureBlobService : IAzureBlobServices
    {
        [WebGet(UriTemplate = "/IsBlobClientOpened", ResponseFormat = WebMessageFormat.Json)]
        public bool IsSLClientOpenedForUser()
        {
            return AzureBrowserConnections.IsSessionOpenedForUser(SPContext.Current.Web.CurrentUser);
        }

        [WebInvoke(Method = "POST", UriTemplate = "/CreateAzureSession", BodyStyle = WebMessageBodyStyle.Bare)]
        public void CreateSession()
        {
            SPUser user = SPContext.Current.Web.CurrentUser;
            if (!AzureBrowserConnections.IsSessionOpenedForUser(user))
            {
                AzureBrowserConnections.AddSession(user);
            }           
        }

        [WebInvoke(Method = "POST",
            UriTemplate = "/SessionTransferBlob?listId={listId}&itemId={itemId}&fieldId={fieldId}&blobId={blobId}&isUpload={isUpload}",
            RequestFormat = WebMessageFormat.Json,  ResponseFormat = WebMessageFormat.Json)]
        public void InitiateBlobTransfert(string listId, string itemId, string fieldId, string blobId, bool isUpload)
        {
            Blob blob = new Blob();
            blob.SiteId = SPContext.Current.Site.ID;
            blob.WebId = SPContext.Current.Web.ID;

            blob.ListId = new Guid(listId);
            blob.FieldId = new Guid(fieldId);
            blob.ItemId = Convert.ToInt32(itemId);
            blob.IsUpload = isUpload;
            blob.Guid = HttpUtility.UrlEncode(Guid.NewGuid().ToString());

            // Giving temp list name for vizualization for upload.
            SPField field = SPContext.Current.Web.Lists[blob.ListId].Fields[blob.FieldId];
            if (isUpload)
            {
                blob.BlobId = String.Format("{0} in {1}", field.Title, SPContext.Current.Web.Lists[blob.ListId].GetItemById(blob.ItemId).Title);
            }
            else
            {
                blob.BlobId = blobId;
            }
            
            // Add reference to the column containing the key of the blob !!!!
            AzureBrowserConnections.AddBlob(SPContext.Current.Web.CurrentUser, blob);
        }

        [WebGet(UriTemplate = "/FetchBlobsToDownload", ResponseFormat = WebMessageFormat.Xml)]
        public List<Blob> fetchBlobsToDownload()
        {
            this.IAmAlive();
            List<Blob> blobs = AzureBrowserConnections.GetBLobs(SPContext.Current.Web.CurrentUser);
            foreach (var blob in blobs)
            {
                AzureStorageManager manager = new AzureStorageManager();
                manager.SetSharedAccessSignatureForBlob(blob);
            }
            return blobs;
        }

        [WebGet(UriTemplate = "/ValidateUpload?guid={guid}&name={name}")]
        public void ValidateBlob(string guid, string name)
        {
            AzureBrowserConnections.ValidateBLob(SPContext.Current.Web.CurrentUser, guid, name);
        }

        [WebGet(UriTemplate = "/IAmAlive")]
        public void IAmAlive()
        {
            AzureBrowserConnections.UpdateUserAlive(SPContext.Current.Web.CurrentUser, DateTime.Now);
        }

        [WebGet(UriTemplate = "/GetShareLink?listId={listId}&itemId={itemId}&fieldId={fieldId}&blobId={blobId}",
            ResponseFormat=WebMessageFormat.Json)]
        public string GetShareLink(string listId, string itemId, string fieldId, string blobId)
        {
            Blob blob = new Blob();
            blob.SiteId = SPContext.Current.Site.ID;
            blob.WebId = SPContext.Current.Web.ID;

            blob.BlobId = blobId;
            blob.ListId = new Guid(listId);
            blob.FieldId = new Guid(fieldId);
            blob.ItemId = Convert.ToInt32(itemId);

            return AzureStorageManager.GetTempUrlForContent(blob);
        }
    }

    [DataContract]
    public class Blob
    {
        [IgnoreDataMember]
        public Guid SiteId;

        [IgnoreDataMember]
        public Guid WebId;

        [IgnoreDataMember]
        public Guid ListId;

        [IgnoreDataMember]
        public Guid FieldId;

        [IgnoreDataMember]
        public bool SentToSLClient = false;

        // Used to keep trace of values in SL.
        [DataMember]
        public string Guid;

        [DataMember(Name="Name")]
        public string BlobId;

        [IgnoreDataMember]
        public int ItemId;

        [DataMember]
        public string SharedAccessSignature;

        [DataMember]
        public bool IsUpload;

        
    }
}
